
import React, { Component, PureComponent } from 'react'

import { Tooltip, Pagination, Table, Alert, Popover, Space, Checkbox, Row, Col, Divider } from 'antd';
import { ReloadOutlined, SettingOutlined, CheckCircleFilled } from '@ant-design/icons';
import { Resizable } from 'react-resizable';
import { nanoid } from 'nanoid'

import { cloneDeep, throttle } from 'lodash'

import './index.less'
import './styles.css'     // 引入 拖拽 功能 样式

const ResizeableTitle = (props) => {
  const { onResize, width, ...restProps } = props;
  if (!width) {
    return <th {...restProps} />
  }
  return (
    <Resizable width={width} height={0} onResize={onResize}>
      <th {...restProps} />
    </ Resizable >
  )
}
export default class MainTable extends PureComponent {

  domId = nanoid()      // 表格的 id

  tableHeadDom = null     // 表头的 DOM

  tableScrollHeight = 0     // 表格 垂直  可 滚动 区域

  components = {
    header: {
      cell: ResizeableTitle,
    }
  }

  state = {
    scrollY: 0,
    selectedRowKeys: []
  }

  constructor(props){
    super(props)
    this.state.columns = props.columns || []
  }

  componentDidMount() {
    this.tableHeadDom = document.getElementById(this.domId).getElementsByClassName("ant-table-header")[0]
  }

  componentDidUpdate() {
    this.updateTableScrollHeight()      //更新 表格 垂直 可滚动 区域 距离
  }

  // handleResize = throttle(index => (e, { size }) => {
  //   console.log('表格 resize  ==== ', e, size)
  //   this.setState(({ columns }) => {
  //     const nextColumns = [...columns];
  //     nextColumns[index] = {
  //       ...nextColumns[index],
  //       width: size.width,
  //     };
  //     return { columns: nextColumns };
  //   })
  // }, 100)

  handleResize = index => (e, { size }) => {
    console.log('表格 resize  ==== ', e, size)
    this.setState(({ columns }) => {
      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width,
      };
      return { columns: nextColumns };
    })
  }

  getTableToTop() {    // 表头底部到 浏览器最上方距离
    let tHeaderBottom = 0
    this.tableHeadDom && (tHeaderBottom = this.tableHeadDom.getBoundingClientRect().bottom)
    return tHeaderBottom
  }

  updateTableScrollHeight = () => {
    const h = this.getTableToTop()
    if (this.tableScrollHeight !== h) {    // 如果不同 就 重新 渲染  表格 的 垂直 滚动区域
      this.tableScrollHeight = h
      this.setState({
        scrollY: `calc(100vh - ${this.tableScrollHeight + 68}px)`
      })
    }
  }

  clearSelection = () => {      // 清空 所有选择
    this.setState({ selectedRowKeys: [] })
  }

  onselectionchange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys: selectedRowKeys })
    const fn = this.props.onselectionchange
    typeof fn === 'function' && fn(selectedRowKeys, selectedRows)
  }

  refresh = () => {
    const { refresh } = this.props
    typeof refresh === 'function' && refresh()
  }

  columnCheckboxOnchange = (item, index) => {
    const { columns } = this.state
    const { hidden } = columns[index]
    columns[index].hidden = !hidden
    this.setState({ columns: cloneDeep(columns) })
  }

  getColumnCheckBox = () => {
    const { columns = [] } = this.state
    return <Row gutter={16} style={{width: '400px'}}>
      {
        columns.map((item, index) => {
          return <Col span={12} key={index}>
            <Checkbox
              checked={!item.hidden}
              onChange={() => { this.columnCheckboxOnchange(item, index) }}>{item.title}</Checkbox>
          </Col>
        })
      }
    </Row>
  }

  clearSelection = () => {
    this.onselectionchange([], [])
  }

  getMessageContent = () => {
    const { selectedRowKeys } = this.state
    return <div className="wrap-div">
      <div className="left-box">
        <span className="wrap-span">
          <CheckCircleFilled style={{ fontSize: '16px', fontWeight: 'bold', marginRight:'6px'}}/>
          已选择 <span className="wrap-span-text">{selectedRowKeys.length }</span> 项
          <span className="wrap-span-clear" onClick={this.clearSelection}>清空</span>
          <Divider type="vertical" style={{ borderLeft: '1px solid rgba(0, 0, 0, 0.2)'}}/>
        </span>
      </div>
      <div className="right-box">
        <Tooltip placement="top" title="刷新">
          <ReloadOutlined className="icon-self-style" onClick={this.refresh} />
        </Tooltip>
        <Popover content={this.getColumnCheckBox()} title='自定义列' placement="rightBottom" trigger="click">
          <Tooltip placement="top" title="列设置">
            <SettingOutlined className="icon-self-style" style={{ marginLeft: '10px' }} />
          </Tooltip>
        </Popover>
      </div>
    </div>
  }

  getRealColumns = () => {
    let { columns = [] } = this.state
    columns = columns.filter(r => !r.hidden)    //  获取到没 隐藏的 列

    return columns.map((col, index) => ({
      ...col,
      onHeaderCell: column => ({
        width: col.width, // 100 没有设置宽度可以在此写死 例如100试下
    	  onResize: this.handleResize(index),
      })
    }))
  }

  render() {

    const { scrollY } = this.state
    const {
      size = 'small',
      noToolBar = false,
      dataSource = [],
      columns = [],
      pagination = {
        total: 0,
        pageSize: 20,
        current: 1,
      },
      rowKey = (row) => row.id,
      onChange = (item) => { console.log(item) },
      selectionType = null,
      selectedRowKeys = this.state.selectedRowKeys,
      // onselectionchange = (selectedRowKeys, selectedRows) => { console.log(selectedRowKeys, selectedRows)},
      getCheckboxProps = (record) => ({}),
      ...rest
    } = this.props

    return (
      <>
        {
          !noToolBar && <Alert className="magin-table-wrap-toolbar clearBoth" message={this.getMessageContent()} type="info" style={{ marginBottom: '4px' }} />

        }
        <Table
          id={this.domId}
          size={size}
          columns={this.getRealColumns()}
          components={this.components}
          rowSelection={selectionType ? {
            selectedRowKeys: selectedRowKeys,
            type: selectionType,    // checkbox 多选  ||  radio 单选
            onChange: this.onselectionchange,
            getCheckboxProps,
          } : null}
          dataSource={dataSource}
          bordered
          scroll={this.props.scroll ? this.props.scroll : { x: 600, y: scrollY }}
          rowKey={rowKey}
          onChange={onChange}
          {...rest}
          pagination={
            Object.assign(
              {
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: total => `共 ${total} 条记录`
              },
              pagination)
          } />
      </>
    )
  }
}
